package mysql

import (
	"bluebell/models"
	"strings"

	"github.com/jmoiron/sqlx"
)

func CreatePost(p *models.Post) (err error) {
	sqlStr := `INSERT INTO post 
	(post_id, author_id, community_id, title, content) 
	VALUES (?,?,?,?,?)`

	_, err = db.Exec(sqlStr, p.ID, p.AuthorID, p.CommunityID, p.Title, p.Content)
	return err
}

func GetPostByID(pid int64) (p *models.Post, err error) {
	p = new(models.Post)
	sqlStr := `SELECT post_id, author_id, community_id, title, content, create_time 
	FROM post 
	WHERE post_id = ?`

	err = db.Get(p, sqlStr, pid)
	return
}

func GetPostList(page, size int64) (postList []*models.Post, err error) {
	sqlStr := `SELECT post_id, author_id, community_id, title, content, create_time 
	FROM post
	ORDER BY create_time DESC 
	Limit ?,?`

	postList = make([]*models.Post, 0, size)
	err = db.Select(&postList, sqlStr, (page-1)*size, size)
	return
}

// 根据给定的id列表获取查询帖子
func GetPostListByIDs(ids []string) (postList []*models.Post, err error) {
	sqlStr := `SELECT post_id, author_id, community_id, title, content, create_time 
	FROM post 
	WHERE post_id IN (?)
	ORDER BY  FIND_IN_SET(post_id, ?)`

	query, args, err := sqlx.In(sqlStr, ids, strings.Join(ids, ","))
	if err != nil {
		return
	}

	query = db.Rebind(query)
	err = db.Select(&postList, query, args...)

	return
}
